package com.innovation.ic.im.end.web.controller.im_erp9;

import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.FileUtil;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.vo.im_erp9.DownloadVo;
import com.innovation.ic.im.end.web.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件API
 */
@Api(value = "文件API", tags = "FileController")
@RestController
@RequestMapping("/api/v1/file")
public class FileController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    /**
     * 下载图片或文档
     *
     * @param downloadVo
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "下载图片或文档")
    @ApiImplicitParam(name = "downloadVo", value = "下载vo类", required = true, dataType = "DownloadVo")
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    public ResponseEntity<ApiResult<Boolean>> downloadCheckReport(@RequestBody DownloadVo downloadVo, HttpServletResponse response) throws IOException {
        if (null == downloadVo || !StringUtils.validateParameter(downloadVo.getFilename()) || downloadVo.getType() == null) {
            String message = "调用接口【/api/v1/file/download时，参数filename与type不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        } else {
            log.info("参数filename为【" + downloadVo.getFilename() + "】");
        }
        String fileName = unicodeToString(downloadVo.getFilename());

        if (downloadVo.getType() == MessageType.FILE.intValue()) {//文件
            boolean result = minioManager.newDownload(minioConfig.getBucketName(), fileName, response, downloadVo.getType());
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(result);
            apiResult.setCode(HttpStatus.OK.value());
            apiResult.setMessage(result ? ServiceResult.SELECT_SUCCESS : ServiceResult.SELECT_FAIL);
            apiResult.setResult(result);
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }

        boolean result = FileUtil.downloadImg(fileParamConfig.getFileUrl(), fileName, response);
        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(result);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result ? ServiceResult.SELECT_SUCCESS : ServiceResult.SELECT_FAIL);
        apiResult.setResult(result);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 对文件名进行解码
     *
     * @param fileName 文件名
     * @return 返回解码结果
     */
    public static String unicodeToString(String fileName) throws UnsupportedEncodingException {
        if (!Strings.isNullOrEmpty(fileName)) {
            fileName = fileName.replaceAll("\\+", "%2B");
            fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
            log.info("解码后的文件名为:[{}]", fileName);
            return fileName;
        }
        return null;
    }
}